import { Body, Controller, Post } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { simpleMd5 } from 'src/common/hash-helper'
import { isNullOrEmptyString } from 'src/common/string-helper'
import { LoginRequest } from 'src/dto/auth/login.action'
import { ResponseBaseWithData } from 'src/dto/response-base'
import { Semantic } from 'src/dto/semantic'
@Controller('auth/login')
export class LoginController {
    constructor(
        private readonly configService: ConfigService,
        private readonly jwtService: JwtService
    ) {}
    @Post()
    login(@Body() request: LoginRequest): ResponseBaseWithData<string> {
        //校验账号密码是否合法
        if (isNullOrEmptyString(request.account)) {
            return { success: false, messageId: Semantic.login.mustHaveAccount, data: null }
        }

        if (isNullOrEmptyString(request.password)) {
            return { success: false, messageId: Semantic.login.mustHavePassword, data: null }
        }

        const account = this.configService.get<string>('account')

        if (account !== request.account) {
            return { success: false, messageId: Semantic.login.accountNotMatch, data: null }
        }

        const password = this.configService.get<string>('password')

        if (password !== simpleMd5(request.password)) {
            return { success: false, messageId: Semantic.login.passwordNotMatch, data: null }
        }

        const payload = {
            account: request.account
        }

        const token = this.jwtService.sign(payload)

        return { success: true, messageId: 'success', data: token }
    }
}
